import {
  Get,
  Post,
  Put,
  Patch,
  Del,
  Inject,
  Query,
  Body,
  ALL,
  Provide,
  Controller,
  Validate,
} from '@midwayjs/decorator';

import { BaseController, ERRCODE, ERRMSG } from '../../../comm/controller';
import { CreateProductDto, UpdateProductDto } from '../dto/product';
import { BasePageDto } from '../dto/base';

import { MallProductService } from '../service/product';
import { MallProductClothingService } from '../service/productClothing';

@Provide()
@Controller('/mall/product')
export class MallProductController extends BaseController {
  @Inject()
  mallProductService: MallProductService;

  @Inject()
  mallProductClothingService: MallProductClothingService;

  @Post('/add')
  @Validate()
  async add(@Body(ALL) product: CreateProductDto) {
    try {
      const data = await this.mallProductService.add(product);
      return this.ok({ product: data });
    } catch (err) {
      return this.fail();
    }
  }

  @Get('/info')
  async info(@Query('id') productId: number) {
    try {
      const data: any = await this.mallProductService.info(productId);
      if (!data) throw new Error('找不到 product.');
      data.sku = await this.mallProductClothingService.list({ productId });
      return this.ok({ product: data });
    } catch (err) {
      return this.fail(ERRCODE.SERVER_COMM_ERROR, err.message);
    }
  }

  @Post('/delete')
  @Del('/delete')
  async delete(@Body('productId') productId: number) {
    try {
      const data = await this.mallProductService.delete(productId);
      return this.ok({ product: data });
    } catch (err) {
      return this.fail();
    }
  }

  @Post('/update')
  @Put('/update')
  @Patch('/update')
  @Validate()
  async update(@Body(ALL) product: UpdateProductDto) {
    try {
      const data = await this.mallProductService.update(product);
      return this.ok({ product: data });
    } catch (err) {
      return this.fail();
    }
  }

  @Get('/page')
  async page(@Query(ALL) op: BasePageDto) {
    try {
      const { data, count } = await this.mallProductService.page(op);
      return this.ok({
        products: data,
        hasMore: op.start + op.limit < count,
        count,
      });
    } catch (err) {
      return this.fail();
    }
  }
}
